package com.amumu.drama.common.config;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;

/**
 * @author sunzhuang
 * @date 2024/5/13 15:02
 * @slogan 天下风云出我辈, 一入代码岁月催
 * @desc Redisson 自动装配配置类
 */

@Slf4j
@ConditionalOnClass(Redisson.class) // 条件装配
@Configuration
@EnableConfigurationProperties({RedisProperties.class, RedissonLockProperties.class})
public class RedissonConfiguration {

    private final static String REDIS_PROTOCOL_PREFIX = "redis://";

    private final static String REDISS_PROTOCOL_PREFIX = "rediss://";

    @Autowired
    private RedisProperties redisProperties;

    @Value("${opentide.redisson.timeout:300}")
    private int timeout;

    @PostConstruct
    public void postConstruct() {
        log.info(" Starter [RedissionClient Starter] Auto Configure.");
    }

    @Bean
    public RedissonClient redissonClient() {
        /**
         * 运行模式 useSingleServer: 单机模式 useMasterSlaveServers: 主从模式 useSentinelServers: 哨兵模式 useClusterServers:集群模式
         */
        Config config = new Config();
        String prefix = REDIS_PROTOCOL_PREFIX;
        Method method = ReflectionUtils.findMethod(RedisProperties.class, "isSsl");
        if (method != null && (Boolean) ReflectionUtils.invokeMethod(method, redisProperties)) {
            prefix = REDISS_PROTOCOL_PREFIX;
        }
        config.useSingleServer().setAddress(REDIS_PROTOCOL_PREFIX + redisProperties.getHost() + ":" + redisProperties.getPort())
                .setUsername(redisProperties.getUsername())
                .setPassword(redisProperties.getPassword())
                .setConnectTimeout(timeout).setDatabase(redisProperties.getDatabase());
        return Redisson.create(config);
    }
}
